package com.easyJava.builder;

import com.easyJava.bean.ClassInfo;
import com.easyJava.bean.Constants;
import com.easyJava.utils.BufferedWriterUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class BuildBase {

    public static void execute(){
        build(null, Constants.PACKAGE_UTILS, "LocalDateUtils", Constants.PATH_UTILS);
        build(null, Constants.PACKAGE_UTILS, "LocalDateTimeUtils", Constants.PATH_UTILS);
        build(null, Constants.PACKAGE_MAPPER, "BaseMapper", Constants.PATH_MAPPER);
        build(null, Constants.PACKAGE_ENUMS, "PageSize", Constants.PATH_ENUMS);
        build(null, Constants.PACKAGE_ENUMS, "DateTimeEnum", Constants.PATH_ENUMS);
        build(null, Constants.PACKAGE_QUERY, "BaseQuery", Constants.PATH_QUERY);
        List<ClassInfo> importClass = new ArrayList<>();
        importClass.add(new ClassInfo(Constants.PACKAGE_ENUMS, "PageSize"));
        build(importClass, Constants.PACKAGE_QUERY, "SimplePage", Constants.PATH_QUERY);
        build(null, Constants.PACKAGE_VO, "PaginationResultVO", Constants.PATH_VO);
        build(null, Constants.PACKAGE_RESULT, "Result", Constants.PATH_RESULT);
    }

    private static void build(List<ClassInfo> importClass, String packageName, String fileName, String outputPath){
        File folder = new File(outputPath);
        folder.mkdirs();
        File javaFile = new File(folder, fileName + ".java");

        try (
            InputStream in = BuildBase.class.getClassLoader().getResourceAsStream("template/" + fileName + ".txt");
            InputStreamReader inr = new InputStreamReader(in, StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(inr);

            OutputStream out = new FileOutputStream(javaFile);
            OutputStreamWriter outw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bufferedWriter = new BufferedWriter(outw);
        ){
            BufferedWriterUtils bw = new BufferedWriterUtils(bufferedWriter);

            bw.write("package " + packageName + ";");
            bw.newLine();

            if(importClass != null){
                for(ClassInfo classInfo : importClass){
                    bw.write("import " + classInfo.getPackagePath() + "." + classInfo.getClassName() + ";");
                }
                bw.newLine();
            }

            String lineInfo = null;
            while((lineInfo = br.readLine()) != null){
                bw.write(lineInfo);
            }

            bw.flush();
        }catch (Exception e){
            log.error("创建" + fileName + "文件失败:{}", e);
        }
    }
}
